/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cassys.action;

import cassys.dataaccess.DAOException;
import cassys.datatransferobjects.LecturerDTO;
import cassys.datatransferobjects.StudentDTO;
import cassys.datatransferobjects.UserDTO;
import cassys.delegates.UserDelegate;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 *
 * @author ASUS
 */
public class UserAction extends CassysSupport {

    private File usersfile;
    private static final long serialVersionUID = -8449783098188762048L;
    private UserDelegate userDelegate = new UserDelegate();
    private boolean isUpdate = false;
    private List<UserDTO> users = new ArrayList<UserDTO>();
    //private String username;
    private String userId;
    private UserDTO user;
    private ArrayList<String> usersImported = new ArrayList<String>();
    private ArrayList<String> usersNotImported = new ArrayList<String>();
    public static final String USER_LIST = "userlist";
    public static final String USER_FORM = "userform";
    public static final String USER_IMPORT = "userimport";
    public static final String USER_UPDATED = "userupdated";

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public UserDTO getUser() {
        return user;
    }

    public void setUser(UserDTO user) {
        this.user = user;
    }

    public List<UserDTO> getUsers() throws Exception {
        users = userDelegate.findAllUsers();
        return users;
    }

    public boolean getUpdate() {
        return isUpdate;
    }

    public void setUpdate(boolean update) {
        isUpdate = update;
    }

    @Override
    public String execute() throws Exception {
        return list();
    }

    public String list() throws Exception {
        //users = userDelegate.findAllUsers();
        return USER_LIST;
    }

    public String importDone() throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader(usersfile));
        String line;

        while ((line = reader.readLine()) != null) {
            try {
                StringTokenizer tokens = new StringTokenizer(line, ",");
                UserDTO tempuser = new UserDTO();
                tempuser.setRole("student");
                tempuser.setUsername(tokens.nextToken());
                tempuser.setPassword(tokens.nextToken());
                tempuser.setEmail(tokens.nextToken());
                userDelegate.insertUser(tempuser);
                usersImported.add(tempuser.getUsername());
            } catch (Exception e) {
                usersNotImported.add(line);
            }

        }
        return "userimport";
    }

    public String create() throws Exception {
        System.out.println("Add " + isUpdate);
        isUpdate = false;
        return USER_FORM;

    }

    public String userimport() throws Exception {
        return "userimport";

    }

    public String importUsers() throws Exception {
        return USER_IMPORT;

    }

    public String edit() throws Exception {

        //user = findUserByName(userId);
        user = findUserById(userId);
        System.out.println("user name" + user.getUsername());
        System.out.println("password " + user.getPassword());
        System.out.println("email " + user.getEmail());
        System.out.println("role " + user.getRole());
        if (user != null) {
            isUpdate = true;
        }

        return USER_FORM;

    }

    public String delete() throws Exception {
        //LOG.info("\ndelete");
        user = findUserById(userId);
        System.out.println("user name" + user.getUsername());
        System.out.println("password " + user.getPassword());
        System.out.println("email " + user.getEmail());
        System.out.println("role " + user.getRole());
        if (user.getRole().equalsIgnoreCase("student")) {
            ((StudentDTO) user).setListOfModules(null);
        } else if (user.getRole().equalsIgnoreCase("lecturer")) {
            ((LecturerDTO) user).setModuleList(null);
        }
        userDelegate.deleteUser(user);
        return USER_UPDATED;
    }

    public String update() throws Exception {

        System.out.println("user id" + user.getUserId());
        System.out.println("user name" + user.getUsername());
        System.out.println("password " + user.getPassword());
        System.out.println("email " + user.getEmail());
        System.out.println("role " + user.getRole());
        userDelegate.updateUser(user);

        return USER_UPDATED;
    }

    public String insert() throws Exception {
        userDelegate.insertUser(user);
        return USER_UPDATED;
    }

    public void validate() {
        if (user != null) {
            if (user.getUsername().trim().length() == 0) {
                //LOG.error("username to short");
                addFieldError("user.username", "Username missing or too short.");
            }
            if (user.getEmail().trim().length() == 0) {
                //LOG.error("email to short");
                addFieldError("user.email", "E-Mail address missing or wrong.");
            }
            if (user.getPassword().trim().length() == 0) {
                //LOG.error("password to short");
                addFieldError("user.password", "Password missing or too short.");
            }
            if (user.getRole().trim().length() == 0) {
                //LOG.error("role to short");
                addFieldError("user.role", "Role missing.");
            }
        }
    }

    private UserDTO findUserById(String userId) {
        System.out.println(userId);
        UserDTO usr = null;
        try {
            usr = userDelegate.findUser(userId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(usr.getEmail());
        return usr;
    }

    /*
     * private UserDTO findUserByName(String name) { UserDTO us = null;
     *
     * try { us = userDelegate.findUser(name); } catch (Exception de) {
     * //LOG.error("\nexception caught in findUserByName method", de); throw new
     * RuntimeException(de); } return us; }
     */
    public void setIsUpdate(boolean isUpdate) {
        this.isUpdate = isUpdate;
    }

    public boolean isIsUpdate() {
        return isUpdate;
    }

    public File getUsersfile() {
        return usersfile;
    }

    public void setUsersfile(File file) {
        this.usersfile = file;
    }

    public ArrayList<String> getUsersImported() {
        return usersImported;
    }
    
    public ArrayList<String> getUsersNotImported() {
        return usersNotImported;
    }    
}
